// miniprogram/pages/signIn/index.js
var util = require('../../utils/util.js')
const user = require('../index/model.js')
var api = require('../../utils/api.js')
const {
  $Message
} = require('../../dist/base/index');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    distance: 0,
    latitude: 0,
    longitude: 0,
    refreshLocation: null,
    sign_result: null,
    spinShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   * 签到表存储内容：
   * user_info_id
   * time_day
   * time_hour_min
   * is_later
   */
  onLoad: function (options) {
    var self = this
    var signDic = this.getSignDic()
    self.setData({
      spinShow: true
    })
    console.log(signDic.time_day)
    //获取状态
    api.db.collection('user_sign_history').where({
      user_info_id: signDic.user_info_id,
      time_day: signDic.time_day
    })
      .get({
        success: function (res) {
          self.setData({
            spinShow: false
          })
          if (res.data.length != 0) {
            //说明今天已经签到
            var result = res.data[0]
            self.setData({
              distance: result.is_later == 'true' ? "迟到" : "已签到",
              sign_result: result,
              spinShow: false
            })
          } else {
            self.setData({
              spinShow: false,
              distance: "Load"
            })
            //开始刷新距离
            self.startRefreshLocation(function () {
              //清除定时器
              clearInterval(self.data.refreshLocation)
              self.setData({
                spinShow: true
              })
              var signDicLeast = self.getSignDic()
              api.db.collection('user_sign_history').where({
                user_info_id: user.user_info._id,
                time_day: signDicLeast.time_day
              }).get().then(res => {
                // res.data 包含该记录的数据
                console.log(res.data)
                if (res.data.length == 0) {
                  api.db.collection('user_sign_history')
                    .add({
                      data: signDicLeast
                    }).then(res => {
                      // res 是一个对象，其中有 _id 字段标记刚创建的记录的 id
                      self.setData({
                        spinShow: false,
                        distance: signDicLeast.is_later == true ? "已签到" : "迟到",
                        sign_result: signDicLeast
                      })
                      $Message({
                        content: "自动签到成功",
                        type: 'success'
                      });
                    }).catch(res => {
                      self.setData({
                        spinShow: false
                      })
                      console.log(res)
                    })
                }
              })
            })
          }
        }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.refreshLocation)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  startRefreshLocation(distFunc) {
    var self = this
    var refreshLocation = setInterval(function () {
      console.log("获取地址")
      //获取地址
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          const latitude = res.latitude
          const longitude = res.longitude
          const speed = res.speed
          const accuracy = res.accuracy
          const dist = util.func.getDistance(latitude, longitude, 32.083106994628906, 118.76947021484375)
          console.log(latitude)
          console.log(longitude)
          console.log(dist)
          self.setData({
            latitude: latitude,
            longitude: longitude,
            distance: parseInt(dist)
          })
          if (parseInt(dist) < 500) {
            distFunc()
          }
        },
        fail(res) {
          console.log(res)
        }
      })
    }, 2000);
    this.setData({
      refreshLocation: refreshLocation
    })
  },
  getSignDic() {
    //获取当前时间戳  
    var timestamp = Date.parse(new Date());
    timestamp = timestamp;
    console.log("当前时间戳为：" + timestamp);
    //获取当前时间  
    var n = timestamp;
    var date = new Date(n);
    //年  
    var Y = date.getFullYear();
    //月  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日  
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    //时  
    var h = date.getHours();
    //分  
    var m = date.getMinutes();
    //秒  
    var s = date.getSeconds();
    var signDic = {}

    signDic.user_info_id = user.user_info._id
    signDic.time_day = Y + M + D
    var h = h < 10 ? '0' + h : h
    var m = m < 10 ? '0' + m : m
    signDic.time_hour_min = h + '' + m
    signDic.is_later = parseInt(signDic.time_hour_min) > 845 ? true : false
    signDic.timestamp = timestamp
    return signDic
  },
  click_history() {
    // this.getSignDic()
    wx.navigateTo({
      url: '/pages/signHistory/index',
    })
  }
})